package model

import (
	"enjoy_xxz/formdata"
	"enjoy_xxz/internal/model/database/mysql"
	"enjoy_xxz/internal/model/goods"
	"enjoy_xxz/pkg"
	"errors"
	"fmt"
	"gorm.io/gorm"
)

// 购物车表的结构体
type Cart struct {
	gorm.Model
	UserID   int64 `gorm:"type:varchar(20);not null;comment:用户ID;"`
	GoodsID  int64 `gorm:"type:varchar(50);not null;comment:商品ID;"`
	Quantity int64 `gorm:"type:varchar(15);comment:购物车商品数量;"`
	SkuID    int64 `gorm:"type:int(11);not null;default:0;comment:属性ID;"`
}

// 添加购物车
func (ca *Cart) CreateCart(quantity int64) error {
	return mysql.WithMysql(func(db *gorm.DB) error {
		//查询购物车 如果有修改 ，没有添加
		err := db.Where("sku_id = ?", ca.SkuID).First(ca).Error
		if err != nil {
			if errors.Is(err, gorm.ErrRecordNotFound) {
				fmt.Println("创建", ca.SkuID)
				return db.Create(&ca).Error
			}
			return err
		}
		fmt.Println("修改", ca.SkuID, quantity)
		return db.Model(ca).Where("sku_id = ?", ca.SkuID).Update("quantity", gorm.Expr("quantity + ?", quantity)).Error
	})
}

// 购物车 列表
func (ca *Cart) GetCartList(userID int64) (cartList []formdata.CartList, err error) {
	var list []Cart
	return cartList, mysql.WithMysql(func(db *gorm.DB) error {
		// 查询购物车列表
		err = db.Where("user_id = ?", userID).Find(&list).Error
		if err != nil {
			return fmt.Errorf("查询购物车列表失败: %v", err)
		}
		fmt.Println("购物车列表 list:", list)

		// 获取所有 skuId
		var ids []int64
		for _, val := range list {
			ids = append(ids, val.SkuID)
		}
		fmt.Println("skuId 列表 ids:", ids)

		// 查询 sku 表
		var skList []goods.GoodsSku
		err = db.Model(&goods.GoodsSku{}).Where("id in (?)", ids).Find(&skList).Error
		if err != nil {
			return fmt.Errorf("查询 sku 表失败: %v", err)
		}
		fmt.Println("sku 表数据 skList:", skList)

		// 构建 skuMap 和 gid
		var gid []int64
		skuMap := make(map[int64]goods.GoodsSku)
		for _, val := range skList {
			skuMap[int64(val.ID)] = val
			gid = append(gid, val.GoodsID)
		}
		fmt.Println("商品ID列表 gid:", gid)

		// 查询商品表
		var goodsInfo []goods.Goods
		err = db.Model(&goods.Goods{}).Where("id in (?)", gid).Find(&goodsInfo).Error
		if err != nil {
			return fmt.Errorf("查询商品表失败: %v", err)
		}

		// 构建 goodMap
		goodMap := make(map[int64]goods.Goods)
		for _, val := range goodsInfo {
			goodMap[int64(val.ID)] = val
		}
		fmt.Println("商品映射 goodMap:", goodMap)

		// 构建购物车列表
		for _, val := range list {
			if res, ok := skuMap[val.SkuID]; ok {
				// 检查 goodMap 中是否存在对应的商品
				if gInfo, ok := goodMap[res.GoodsID]; ok {
					Images := pkg.GetImages(gInfo.Img) // 解析json格式图片
					cartList = append(cartList, formdata.CartList{
						SkuId:       int64(res.ID),
						GoodsId:     res.GoodsID,
						Stock:       res.Stock,
						Price:       res.Price,
						VipPrice:    res.VipPrice,
						ProValueId1: res.ProValueID1,
						ProValueId2: res.ProValueID2,
						ProValueId3: res.ProValueID3,
						Title:       gInfo.Title,
						Img:         Images,
						Quantity:    val.Quantity,
					})
				} else {
					fmt.Printf("商品ID %d 未找到对应的商品信息\n", res.GoodsID)
				}
			}
		}
		fmt.Println("最终购物车列表 cartList:", cartList)
		return nil
	})
}

// 购物车 修改数量
func (ca *Cart) CartUpdateByQuantity(userID int64) error {
	return mysql.WithMysql(func(db *gorm.DB) error {
		return db.Model(ca).Where("user_id = ?", userID).Where("sku_id = ?", ca.SkuID).
			Update("quantity = ?", ca.Quantity).Error
	})
}
